﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Infrastructure.Lib.Core;

namespace Infrastructure.Lib.Core
{
    public class NamedList<T> : List<T>
    {
        /// <summary>
        /// NamedList内部已经自动将Name转为小写，外部使用，无需要再进行小写处理
        /// </summary>
        public string Name { get; set; }
        public NamedList<T> result;

        public static bool ConveterFromString(object result, string source)
        {
            if (source.IsNullOrEmpty()) return false;

            List<string> valueList = null;

            bool valid = !source.StartsWith("[") && !source.EndsWith("]");
            if (valid)
            {
                valueList = new List<string>() { source };
            }
            else
            {
                string values = source.Substring(source.IndexOf('[') + 1).Replace("]", "");
                valueList = values.Split(',').ToList();
            }

            TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
            bool canConvertFrom = converter.CanConvertFrom(typeof(string));

            if (!canConvertFrom) return false;

            var add = result.GetType().GetMethod("Add");
            valueList.ForEach(t =>
            {
                var item = new object[] { converter.ConvertFrom(t.Trim()) };
                add.Invoke(result, item);
            });

            if (result.GetType().GetGenericTypeDefinition() == typeof(NamedList<>))
            {
                if (source.IndexOf('[') == -1)
                {
                    return false;
                }
                var name = source.Substring(0, source.IndexOf('['));
                result.GetType().GetProperty("Name").SetValue(result, name.ToLower(), null);
            }
            return true;
        }

        public static implicit operator NamedList<T>(string source)
        {
            NamedList<T> result = new NamedList<T>();
            if (!ConveterFromString(result, source))
                //throw new ArgumentException("无法转换指定的字符串");
                return null;

            return result;
        }
    }
}